class Solution
{
public:
    vector<int> pondSizes(vector<vector<int>> &land)
    {
        vector<int> result;
        int m = land.size();
        int n = land[0].size();

        int dx[8] = {0, 1, 0, -1, 1, -1, 1, -1};
        int dy[8] = {1, 0, -1, 0, 1, -1, -1, 1};

        auto bfs = [&](int startI, int startJ)
        {
            queue<pair<int, int>> q;
            q.push({startI, startJ});
            land[startI][startJ] = -1;
            int area = 0;
            while (!q.empty())
            {
                auto [i, j] = q.front();
                q.pop();
                ++area;
                for (int direction = 0; direction < 8; ++direction)
                {
                    int nextI = i + dx[direction];
                    int nextJ = j + dy[direction];
                    if (nextI < 0 || nextJ < 0 || nextI >= m || nextJ >= n)
                    {
                        continue;
                    }
                    if (land[nextI][nextJ] == 0)
                    {
                        land[nextI][nextJ] = -1;
                        q.push({nextI, nextJ});
                    }
                }
            }
            return area;
        };

        for (int i = 0; i < m; ++i)
        {
            for (int j = 0; j < n; ++j)
            {
                if (land[i][j] != 0)
                {
                    continue;
                }
                result.push_back(bfs(i, j));
            }
        }

        sort(result.begin(), result.end());
        return result;
    }
};